<!-- 微信小程序 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 微信小程序列表 -->
      <el-col :lg="24" :xs="24">
        <!-- <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="微信小程序名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />
                搜索
              </el-button>
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div> -->

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <el-button type="success" @click="handleOpenDialog()">
                  <i-ep-plus />
                  新增
                </el-button>
                <!-- <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                >
                  <i-ep-delete />
                  批量删除
                </el-button> -->
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="编号"
              align="center"
              prop="id"
              width="40"
            />
            <el-table-column
              key="appId"
              label="appId"
              align="center"
              prop="appId"
              width="200"
            />
            <el-table-column
              key="description"
              label="描述"
              align="center"
              prop="description"
              width="140"
            />

            <el-table-column
              key="appSecret"
              label="appSecret"
              align="center"
              prop="appSecret"
              width="220"
            />

            <el-table-column label="关于我们" width="210" align="center">
              <template #default="scope">
                <el-text truncated>{{ scope.row.aboutUs }}</el-text>
              </template>
            </el-table-column>

            <el-table-column label="隐私政策" width="210" align="center">
              <template #default="scope">
                <el-text truncated>{{ scope.row.privacyPolicy }}</el-text>
              </template>
            </el-table-column>
            <el-table-column label="协议" align="center" width="210">
              <template #default="scope">
                <el-text truncated>{{ scope.row.userAgreement }}</el-text>
              </template>
            </el-table-column>

            <el-table-column
              label="更新时间"
              align="center"
              prop="updatedAt"
              width="180"
            >
              <template #default="scope">
                <text>
                  {{
                    new Date(scope.row.updatedAt)
                      .toISOString()
                      .replace("T", " ")
                      .substring(0, 19)
                  }}
                </text>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="160">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleOpenDialog(scope.row.id)"
                >
                  <i-ep-edit />
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.current"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          /> -->
        </el-card>
      </el-col>
    </el-row>

    <!-- 微信小程序表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      style="width: 100vw"
      @close="handleCloseDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="appId" prop="appId">
          <el-input v-model="formData.appId" placeholder="请输入appId" />
        </el-form-item>

        <el-form-item label="appSecret" prop="appSecret">
          <el-input
            v-model="formData.appSecret"
            placeholder="请输入appSecret"
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" placeholder="请输入描述" />
        </el-form-item>

        <el-form-item label="用户协议" prop="userAgreement">
          <el-input
            v-model="formData.userAgreement"
            placeholder="请输入用户协议"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="隐私政策" prop="privacyPolicy">
          <el-input
            v-model="formData.privacyPolicy"
            placeholder="请输入隐私政策"
          />
        </el-form-item>
        <el-form-item label="关于我们" prop="aboutUs">
          <el-input v-model="formData.aboutUs" placeholder="请输入关于我们" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "WxProgram",
  inheritAttrs: false,
});

import wxprogramAPI, {
  WxProgramQuery,
  WxProgramForm,
  WxProgramVO,
} from "@/api/wxprograms";

// const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<WxProgramVO[]>();
/** 微信小程序查询参数  */
const queryParams = reactive<WxProgramQuery>({
  current: 1,
  pageSize: 10,
});

/**  微信小程序弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

// 微信小程序表单数据
const formData = reactive<WxProgramForm>({
  id: undefined,
  appId: "",
  appSecret: "",
  description: "",
  userAgreement: "",
  privacyPolicy: "",
  aboutUs: "",
});

/** 微信小程序表单校验规则  */
const rules = reactive({
  appId: [{ required: true, message: "appId不能为空", trigger: "blur" }],
  appSecret: [
    { required: true, message: "appSecret不能为空", trigger: "blur" },
  ],
  description: [{ required: true, message: "描述不能为空", trigger: "blur" }],
  userAgreement: [
    { required: true, message: "用户协议不能为空", trigger: "blur" },
  ],
  privacyPolicy: [
    { required: true, message: "隐私政策不能为空", trigger: "blur" },
  ],
  aboutUs: [{ required: true, message: "关于我们不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  wxprogramAPI
    .getWxProgram()
    .then((data) => {
      console.log(data, "小程序列表");
      pageData.value = data;
      total.value = 2;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  // queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改微信小程序";
    wxprogramAPI.getWxProgramById(id).then((data) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增微信小程序";
  }
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      wxprogramAPI
        .updateWxProgram(formData)
        .then(() => {
          if (userId) {
            ElMessage.success("修改微信小程序成功");
          } else {
            ElMessage.success("新增微信小程序成功");
          }
          handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除微信小程序 */
function handleDelete(id?: any) {
  const userIds = [id || removeIds.value].join(",");

  ElMessageBox.confirm("确认删除微信小程序?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      wxprogramAPI
        .deleteWxProgram(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
